package com.banciyuan.bcywebview.biz.detail.mixweb;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Browser;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.TimelineLikeHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.dialog.ChargeSuccDialog;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.foldview.FoldLayout;
import com.banciyuan.bcywebview.base.view.scrollview.MyScrollView;
import com.banciyuan.bcywebview.base.view.tag.TagView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.base.view.webview.ObservableWebView;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleSmoothActivity;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleTagSmoothActivity;
import com.banciyuan.bcywebview.biz.detail.EditActivity;
import com.banciyuan.bcywebview.biz.detail.adapter.DetailConstants;
import com.banciyuan.bcywebview.biz.detail.charge.ChargeRankActivity;
import com.banciyuan.bcywebview.biz.detail.charge.ChargeSelectActivity;
import com.banciyuan.bcywebview.biz.detail.comment.CommentConstants;
import com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity;
import com.banciyuan.bcywebview.biz.detail.complex.helper.ComplexHelper;
import com.banciyuan.bcywebview.biz.detail.complex.holder.FloatBottom;
import com.banciyuan.bcywebview.biz.detail.complex.holder.FloatTop;
import com.banciyuan.bcywebview.biz.detail.mixweb.bridge.ImageBridge;
import com.banciyuan.bcywebview.biz.detail.mixweb.bridge.ReaderBridge;
import com.banciyuan.bcywebview.biz.event.EventDetailActivity;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.biz.web.WebActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.util.CommonUtils;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.regex.MyRegex;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.sys.SystemUtils;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;

import de.greenrobot.daoexample.model.ChargeItem;
import de.greenrobot.daoexample.model.Complex;
import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.PostCore;
import de.greenrobot.daoexample.model.Profile;
import de.greenrobot.daoexample.model.Role;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Timeline;

import static com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity.GOCHARGE;
import static com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity.GOSHARE;

/**
 * Created by squall on 2016/11/22.
 */

public class MixWebActivity extends BaseActivity implements BaseWatcher, View.OnClickListener {

    private ObservableWebView mWebView;
    private FoldLayout foldLayout;

    private ImageBridge imageBridge;
    private ReaderBridge readerBridge;

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private int height;
    private int overHeight;

    private LinearLayout mTop;
    private TextView mTitle;
    private FrameLayout mBack;
    private ImageView mHeaderImage;
    private TagView mTag;
    private ImageView ivHeaderRightAction;

    private View rl_header;
    private View rl_bottom;
    private FloatTop contentHeader;
    private FloatBottom floatBottom;
    private FloatTop floatHeader;

    private LinearLayout needFans_ll;
    private LinearLayout needlogin_ll;
    private LinearLayout lockcontral_ll;
    private TextView lockReason_tv;
    private TextView lockUpdate_tv;
    private TextView lockPost_tv;
    private TextView lockCheck_tv;
    private RelativeLayout lock_rl;
    private TextView setFans_tv;
    private TextView login_tv;
    private MyScrollView myScrollView;
    private TextView comment_guide;
    private View comment_cover;

    private DetailType mDetailType;
    private Complex complex;
    private ComplexHelper complexHelper;

    private String from;
    private boolean pushSource;

    private boolean isRlBottomShowing = true;
    private boolean isBottomAnimRunning = false;
    private boolean isTopAnimRunning = false;
    private boolean isRlTopShowing = false;

    private boolean is_folded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mixweb);
        initArgs();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(MixWebActivity.class, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(MixWebActivity.class);
    }

    @Override
    protected void initArgs() {
        from = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        pushSource = getIntent().getBooleanExtra("pushSource", false);
        complex = (Complex) getIntent().getSerializableExtra("complex");
        intiDetailType();
        complexHelper = new ComplexHelper(getContext(), mDetailType);

    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi() {
        myScrollView = (MyScrollView) findViewById(R.id.scrollView);
        foldLayout = (FoldLayout) findViewById(R.id.fold_header);
        mTitle = (TextView) findViewById(R.id.float_title);
        mBack = (FrameLayout) findViewById(R.id.main_back);
        mHeaderImage = (ImageView) findViewById(R.id.float_background);
        mTag = (TagView) findViewById(R.id.float_tags);
        mTop = (LinearLayout) findViewById(R.id.top_header);
        ivHeaderRightAction = (ImageView) findViewById(R.id.iv_longarticle_header_right_action);
        contentHeader = new FloatTop(View.inflate(this, R.layout.detail_head_top, null), 0);
        comment_guide = (TextView) findViewById(R.id.comment_guide);
        comment_cover = findViewById(R.id.comment_cover);

        rl_header = findViewById(R.id.rl_title_top);
        rl_bottom = findViewById(R.id.rl_bottom);

        floatHeader = new FloatTop(rl_header);
        floatBottom = new FloatBottom(rl_bottom, this);
        mTop.addView(contentHeader.getRoot());

        lockReason_tv = (TextView) findViewById(R.id.locked_reason);
        lockUpdate_tv = (TextView) findViewById(R.id.update_btn);
        lockPost_tv = (TextView) findViewById(R.id.post_update_btn);
        needFans_ll = (LinearLayout) findViewById(R.id.ll_needfans);
        needlogin_ll = (LinearLayout) findViewById(R.id.ll_needlogin);
        lock_rl = (RelativeLayout) findViewById(R.id.ll_detail_locked);
        lockcontral_ll = (LinearLayout) findViewById(R.id.fix_container);
        lockCheck_tv = (TextView) findViewById(R.id.post_update_btn_lock);
        setFans_tv = (TextView) findViewById(R.id.tv_setfans);
        login_tv = (TextView) findViewById(R.id.tv_login);

        mWebView = (ObservableWebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

//        mWebView.setWebContentsDebuggingEnabled(true);

    }

    @Override
    protected void initData() {
        renderdata();
    }

    private void renderdata() {
        if (complex == null) return;
        processRightAction();
        if (complex.getStatus() == MyConstants.NEED_FANS && complex.getLock() == null) {
            needFans_ll.setVisibility(View.VISIBLE);
            setFans_tv.setOnClickListener(this);
            mTitle.setVisibility(View.GONE);
            mTag.setVisibility(View.GONE);
            contentHeader.getRoot().setVisibility(View.GONE);
            mProgressbarHelper.onSuccess();
        } else if (complex.getLock() != null) {

            View view = findViewById(R.id.delete_lock);
            view.setVisibility(View.VISIBLE);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDel();
                }
            });

            lockcontral_ll.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(complex.getLock().getReason())) {
                lockReason_tv.setText(Html.fromHtml(complex.getLock().getReason()));
            } else {
                lockReason_tv.setText(getString(R.string.daily_locked_one));
            }
            lock_rl.setVisibility(View.VISIBLE);
            mProgressbarHelper.onSuccess();
        } else if (complex.getStatus() == MyConstants.WORK_LOKED) {
            lock_rl.setVisibility(View.VISIBLE);
            lockcontral_ll.setVisibility(View.GONE);
            lockReason_tv.setText(getString(R.string.daily_locked_one));
            mProgressbarHelper.onSuccess();
        } else if (complex.getStatus() == MyConstants.NEED_LOGIN) {
            needlogin_ll.setVisibility(View.VISIBLE);
            login_tv.setOnClickListener(this);
            mTitle.setVisibility(View.GONE);
            mTag.setVisibility(View.GONE);
            contentHeader.getRoot().setVisibility(View.GONE);
            mProgressbarHelper.onSuccess();
        } else {
            if (StringUtil.notNullEqual(from, "fromComment")) {
                from = "";
                contentHeader.getRoot().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        goComment(true, complex.getReply_count() == 0);
                    }
                }, 200);
                return;
            }
            needFans_ll.setVisibility(View.GONE);
            contentHeader.processTopHeadData(complex, this);
            floatHeader.processTopHeadData(complex, this);
            floatBottom.processBottom(complex);

            ImageLoader.getInstance().displayImage(complex.getCover(), mHeaderImage, ImageOptions.options);
            if (!TextUtils.isEmpty(complex.getTitle())) {
                mTitle.setVisibility(View.VISIBLE);
                mTitle.setText(Html.fromHtml(complex.getTitle()));
            } else {
                mTitle.setVisibility(View.GONE);
            }
            randomCommentGuide();
            renderTags();
            renderWeb();
            judgeFirstShowCommentPic();
        }
    }

    private void judgeFirstShowCommentPic() {
        if (!SPHelper.getBoolean(this, SPConstant.FIRST_SHOW_COMMENT_PIC, false)) {
            comment_cover.setVisibility(View.VISIBLE);
            comment_cover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    comment_cover.setVisibility(View.GONE);
                    SPHelper.putBoolean(MixWebActivity.this, SPConstant.FIRST_SHOW_COMMENT_PIC, true);
                }
            });
        }
    }


    private void renderTags() {
        if (complex.getPost_tags() != null) {
            mTag.setVisibility(View.VISIBLE);
            List<TagDetail> templist = new ArrayList<>();
            if (!TextUtils.isEmpty(complex.getWork())) {
                templist.add(new TagDetail(complex.getWid(), complex.getWork(), complex.getWork()));
            }
            templist.addAll(complex.getPost_tags());
            mTag.setTlist(templist);
            mTag.setTagViewClick(new TagView.OnTagClickListener() {
                @Override
                public void onClick(TagDetail t) {
                    if (!TextUtils.isEmpty(t.getWork())) {
                        if (!TextUtils.isEmpty(t.getWid())) {
                            Intent intent = new Intent(MixWebActivity.this, CircleSmoothActivity.class);
                            intent.putExtra(gotoUtil.INTENT_VALUE_ONE, t.getWork());
                            intent.putExtra(gotoUtil.INTENT_VALUE_TWO, t.getWid());
                            startActivity(intent);
                        }
                    } else if (!TextUtils.isEmpty(t.getEvent_id())) {
                        gotoUtil.gotoAct(MixWebActivity.this, EventDetailActivity.class, t.getEvent_id());
                    } else {
                        Intent intent = new Intent(MixWebActivity.this, CircleTagSmoothActivity.class);
                        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, t.getTag_name());
                        intent.putExtra("type", "tag");
                        startActivity(intent);
                    }
                }
            });
        } else {
            mTag.setVisibility(View.GONE);
        }
    }

    private void processRightAction() {
        Profile profile = complex.getProfile();
        if (null != profile) {
            ivHeaderRightAction.setVisibility(View.VISIBLE);
            if (StringUtil.notNullEqual(profile.getUid(), UserDataHelper.getInstance(this).getUid())) {
                ivHeaderRightAction.setImageResource(R.drawable.detail_more_black);
                ivHeaderRightAction.setAlpha(0.4f);
            } else {
                ivHeaderRightAction.setImageResource(R.drawable.detail_share_black);
                ivHeaderRightAction.setAlpha(1f);
            }
            ivHeaderRightAction.setOnClickListener(this);
        } else {
            ivHeaderRightAction.setVisibility(View.GONE);
        }
    }

    private void alertDel() {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.confrim_to_delete))
                .setActionString(getString(R.string.mydialog_delete))
                .setCancelString(getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delPost();
                    }
                })
                .create().show();
    }

    public void delPost() {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, MixWebActivity.this)) {
                    BaseObserver.getInstance().notifyWatchers(BaseObserver.DELETE_EVENT);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        };
        CommonApiUtils.delPost(this, VolleyQueue.getRquest(this), onSuccess, onError, complex);
    }

    private void renderWeb() {
        mTitle.setVisibility(View.VISIBLE);
        mTag.setVisibility(View.VISIBLE);
        contentHeader.getRoot().setVisibility(View.VISIBLE);

        foldLayout.measure(View.MeasureSpec.makeMeasureSpec(CommonUtils.getWidthPixels(this), View.MeasureSpec.AT_MOST),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        height = foldLayout.getMeasuredHeight();
        overHeight = height - SystemUtils.getScreenHeight(this) + SystemUtils.getStatusBarHeight(this);
        foldLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height));

        ImageBridge imageBridge = new ImageBridge(this);
        imageBridge.setComplex(complex);
        ReaderBridge readerBridge = new ReaderBridge(this, height, new ReaderBridge.OnLoadingComplate() {
            @Override
            public void onComplate() {
                mProgressbarView.post(new Runnable() {
                    @Override
                    public void run() {
                        mProgressbarHelper.onSuccess();
                    }
                });
            }
        });
        readerBridge.setComplex(complex);
        imageBridge.setOnLoadImageSucc(new ImageBridge.OnLoadImageSucc() {
            @Override
            public void onSucc(final String imageUri, final String localUri) {
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadUrl("javascript:onImageLoadSuccess('" + imageUri + "','" + localUri + "')");
                    }
                });
            }

            @Override
            public void onFail(final String imageUri) {
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.loadUrl("javascript:onImageLoadFailed('" + imageUri + "')");
                    }
                });
            }
        });

        mWebView.addJavascriptInterface(imageBridge, "ImageBridge");
        mWebView.addJavascriptInterface(readerBridge, "ReaderBridge");

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http")) {
                    onReaderATagClick("bcyapp_" + url);
                    return true;
                } else {
                    return true;
                }
            }
        });

        mWebView.loadUrl("file:///android_asset/webview/html/reader.html");
    }

    @Override
    protected void initAction() {
        mBack.setOnClickListener(this);
        setFans_tv.setOnClickListener(this);
        mWebView.setOnScrollChangedCallback(new ObservableWebView.OnScrollChangedCallback() {
            @Override
            public void onScroll(int l, int t, int changeL, int changeT) {
                if (changeT < 0) {
                    if (t < height)
                        foldLayout.changeHeader(changeT);
                } else {
                    foldLayout.changeHeader(changeT);
                }
                if (!is_folded) {
                    if (isRlTopShowing && !isTopAnimRunning) {
                        hideTop();
                    }
                    return;
                }
                if (changeT > 5 && isRlBottomShowing && !isBottomAnimRunning) {
                    hideBottom();
                } else if (changeT < -5 && !isRlBottomShowing && !isBottomAnimRunning) {
                    showBottom();
                }
                if (changeT < -5 && !isRlTopShowing && !isTopAnimRunning) {
                    showTop();
                } else if (changeT > 5 && isRlTopShowing && !isTopAnimRunning) {
                    hideTop();
                }
            }

            @Override
            public void onBottom() {
                showBottom();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!isRlBottomShowing && !isBottomAnimRunning) {
                            showBottom();
                        }
                        if (is_folded && !isRlTopShowing && !isTopAnimRunning) {
                            showTop();
                        }

                    }
                }, 100);
            }

            @Override
            public void onTop() {
                if (isRlTopShowing && !isTopAnimRunning) {
                    hideTop();
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            hideTop();
                        }
                    }, 200);
                }
            }
        });

        foldLayout.setOnFoldComplate(new FoldLayout.OnFoldComplate() {
            @Override
            public void folded() {
                myScrollView.scrollTo(0, overHeight);
                is_folded = true;
            }

            @Override
            public void unfolder() {
                is_folded = false;
            }

            @Override
            public void folding(float percent, int height) {
                if (height <= overHeight && overHeight > 0 && percent > 0) {
                    myScrollView.scrollTo(0, height);
                } else if (height > overHeight && overHeight > 0 && percent > 0) {
                    if (myScrollView.getScrollY() < overHeight) {
                        myScrollView.scrollTo(0, overHeight);
                    }
                }
            }
        });
    }

    protected void showTop() {
        if (null == rl_header)
            return;
        ObjectAnimator.ofFloat(floatHeader.getRoot(), "translationY", UIUtils.dip2px(60, this))
                .setDuration(200).start();
        isTopAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlTopShowing = true;
                isTopAnimRunning = false;
            }
        }, 200);
    }

    protected void hideTop() {
        if (null == rl_header)
            return;
        ObjectAnimator.ofFloat(floatHeader.getRoot(), "translationY", 0)
                .setDuration(200).start();
        isTopAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlTopShowing = false;
                isTopAnimRunning = false;
            }
        }, 200);
    }

    protected void showBottom() {
        if (null == rl_bottom) return;
        ObjectAnimator.ofFloat(rl_bottom, "translationY", 0)
                .setDuration(200).start();
        isBottomAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlBottomShowing = true;
                isBottomAnimRunning = false;
            }
        }, 200);
    }

    protected void hideBottom() {
        if (null == rl_bottom)
            return;
        ObjectAnimator.ofFloat(rl_bottom, "translationY", UIUtils.dip2px(66, this))
                .setDuration(200).start();
        isBottomAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlBottomShowing = false;
                isBottomAnimRunning = false;
            }
        }, 200);
    }

    public void onReaderATagClick(String url) {
        try {
            Matcher matcher = MyRegex.plist.get(0).matcher(url);
            if (matcher.find()) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
                startActivity(intent);
            } else {
                goWeb(url);
            }
        } catch (Exception e) {
            goWeb(url);
        }
    }

    private void goWeb(String url) {
        if (url.contains("bcyapp_")) {
            url = url.substring(7);
        }
        Intent intent = new Intent();
        intent.setClass(this, WebActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, url);
        startActivity(intent);
    }

    private void intiDetailType() {
        mDetailType = new DetailType();
        Intent intent = getIntent();
        DetailDataHelper.getBaseDetailVaule(mDetailType, intent);
    }

    private void gotoChargeRank() {
        ChargeItem chargeItem = new ChargeItem();
        if (complex.getTimelineType() != TimelineFactory.TIMELINE_TYPE_DAILY) {
            chargeItem.setPost_id(complex.getRp_id());
        } else {
            chargeItem.setPost_id(complex.getUd_id());
        }
        chargeItem.setPost_type(TimelineFactory.getTimeLineTypeName(complex.getTimelineType()));
        gotoUtil.gotoAct(this, ChargeRankActivity.class, chargeItem);
    }

    private void showCharge() {
        rl_header.post(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(MixWebActivity.this, ChargeSelectActivity.class);
                intent.putExtra("content", complex.getPayment().getIntro());
                if (complex.getTimelineType() != TimelineFactory.TIMELINE_TYPE_DAILY) {
                    intent.putExtra("post_id", complex.getRp_id());
                } else {
                    intent.putExtra("post_id", complex.getUd_id());
                }
                intent.putExtra("uid", complex.getProfile().getUid());
                intent.putExtra("type", TimelineFactory.getTimeLineTypeName(complex.getTimelineType()));
                startActivityForResult(intent, GOCHARGE);
                overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
            }
        });
    }

    private void showRecommend() {
        TimelineLikeHelper.doRecommendAll(this, VolleyQueue.getRquest(this), mDetailType, String.valueOf(complex.isHave_tuijian()), new TimelineLikeHelper.TimelineSuccess() {
            @Override
            public void onTimelineSuccess() {
                complex.setHave_tuijian(!complex.isHave_tuijian());
                floatBottom.updateTuijian(complex);
            }
        });
    }

    private void showDing() {
        complexHelper.doLike(complex, new TimelineLikeHelper.TimelineSuccess() {
            @Override
            public void onTimelineSuccess() {
                if (complex.isHave_ding()) {
                    complex.setDing_num(complex.getDing_num() - 1);
                    complex.setHave_ding(false);
                } else {
                    complex.setDing_num(complex.getDing_num() + 1);
                    complex.setHave_ding(true);
                }
                floatBottom.updateDing(complex);
            }
        });
    }

    protected void showShare() {
        boolean showDelBtn = UserDataHelper.ifLogin(this) && StringUtil.notNullEqual(complex.getProfile().getUid(), UserDataHelper.getInstance(this).getUid());
        Intent intent = new Intent();
        intent.setClass(this, ShareActivity.class);
        intent.putExtra("showDelBtn", showDelBtn);
        intent.putExtra("timeline", parseComplexToTimeline(complex));
        startActivityForResult(intent, GOSHARE);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private Timeline parseComplexToTimeline(Complex complex) {
        Timeline shareTimeline = new Timeline();
        shareTimeline.setContentAddress(complex.getCover());
        shareTimeline.setTitle(complex.getTitle());
        shareTimeline.setOUName(complex.getProfile().getUname());
        shareTimeline.setTimelineType(mDetailType.getTimelineType());
        shareTimeline.setUd_id(mDetailType.getUd_id());
        shareTimeline.setUid(complex.getProfile().getUid());
        shareTimeline.setTags(complex.getPost_tags());
        shareTimeline.setWork(complex.getWork());
        shareTimeline.setType(complex.getType());
        ArrayList<String> roleNames = new ArrayList<>();
        if (complex.getProperties().getCharacter() != null) {
            for (Role role : complex.getProperties().getCharacter()) {
                roleNames.add(role.getRole_name());
            }
            shareTimeline.setOriginalRoleNames(roleNames);
        }
        return shareTimeline;
    }


    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.FOLLOW_EVENT:
                contentHeader.focus_tv.setVisibility(View.GONE);
                floatHeader.focus_tv.setVisibility(View.GONE);
                break;
            case BaseObserver.DELETE_EVENT:
                finish();
                break;
            case BaseObserver.CHARGE_EVENT:
                showCharge();
                break;
            case BaseObserver.CHARGE_RANK:
                gotoChargeRank();
                break;
            case BaseObserver.RECOMMEND_EVENT:
                showRecommend();
                break;
            case BaseObserver.LIKE_EVENT:
                showDing();
                break;
            case BaseObserver.SHARE_EVENT:
                showShare();
                break;
            case BaseObserver.FINISH_EVENT:
                finish();
                break;
            case BaseObserver.COMMENT_EVENT:
                goComment(false, (int) object == 0);
                break;
            case BaseObserver.GO_PERSON:
                Intent intent = new Intent(this, SmoothPersonActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, complex.getProfile().getUid());
                startActivityForResult(intent, ComplexDetailActivity.GOPERSON);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_setfans:
                TimelineLikeHelper.doFollow(this, "dofollow", complex.getProfile().getUid(), new TimelineLikeHelper.FollowSuccess() {
                    @Override
                    public void onFollowSuccess(String response) {
                        if (StatusCodeUtils.dealStatusCode(response, MixWebActivity.this)) {
                            MyToast.show(MixWebActivity.this, getString(R.string.focus_succ));
                            initData();
                        }
                    }
                });
                break;
            case R.id.main_back:
                finish();
                break;
            case R.id.iv_longarticle_header_right_action:
                showShare();
                break;
            case R.id.tv_login:
                gotoUtil.gotoAct(this, LoginActivity.class);
                break;
        }
    }

    private void goComment(boolean refresh, boolean showEdit) {
        Intent intent = new Intent(this, MixWebCommentActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, complex.getUid());
        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, mDetailType);
        intent.putExtra(gotoUtil.INTENT_VALUE_THREE, complex.getReply_count());
        intent.putExtra(gotoUtil.INTENT_VALUE_FOUR, showEdit);
        intent.putExtra(CommentConstants.COMMENT_HINT, comment_guide.getText().toString());

        if (refresh) {
            startActivityForResult(intent, ComplexDetailActivity.GOPERSON);
            overridePendingTransition(R.anim.fast_fade_in, R.anim.fast_fade_out);
        } else {
            startActivity(intent);
        }
    }

    private void randomCommentGuide() {
        String[] array = null;
        if (complex.getReply_count() == 0) {
            array = getResources().getStringArray(R.array.reply_0_content);
        } else {
            array = getResources().getStringArray(R.array.reply_not_0_content);
        }
        Random random = new Random();
        String text = array[random.nextInt(array.length - 1)];
        if (!TextUtils.isEmpty(text)) {
            comment_guide.setText(text);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ComplexDetailActivity.GOPERSON) {
            mProgressbarHelper.onLoading();
            initData();
        } else if (requestCode == GOSHARE) {
            if (resultCode == ShareActivity.DELETE) {
                finish();
            } else if (resultCode == DetailConstants.EDIT_TAGS) {
                List<TagDetail> tags = (List<TagDetail>) data.getSerializableExtra("tags");
                complex.setPost_tags(tags);
                PostCore postCore = (PostCore) data.getSerializableExtra("postcore");
                if (null != postCore) {
                    complex.setWork(postCore.getName());
                    complex.setWid(postCore.getId());
                    complex.setPost_core(postCore);
                }
                mWebView.post(new Runnable() {
                    @Override
                    public void run() {
                        mProgressbarHelper.onLoading();
                        renderTags();
                        mProgressbarHelper.onSuccess();
                    }
                });
            }

        } else if (requestCode == GOCHARGE) {
            if (resultCode == ChargeSelectActivity.PAY_SUCC) {
                if (!isFinishing() && data != null) {
                    boolean showNormalDialog = data.getBooleanExtra("under_700", true);
                    ChargeSuccDialog chargeSuccDialog = new ChargeSuccDialog(this, R.style.Dialog);
                    chargeSuccDialog.showNormalPic(showNormalDialog);
                    chargeSuccDialog.setDetailType(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getContext(), EditActivity.class);
                            intent.putExtra(CommentConstants.CONTENT, getContext().getString(R.string.dafult_pay_comment));
                            intent.putExtra(CommentConstants.SHOW_CHARGE, true);
                            intent.putExtra(CommentConstants.COMMENT_TYPE, 3);
                            DetailDataHelper.putBaseDetailValue(intent, mDetailType);
                            startActivityForResult(intent, CommentConstants.GO_COMMENT);
                            overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                        }
                    });
                    chargeSuccDialog.show();
                }
            }
        }
    }
}
